<template>
  <div
    class="bg-white text-#333639 transition-all f-y-c w-full pl-16 h-50 global-tab"
    dark="bg-dark text-white text-opacity-82 b-dark"
  >
    <div ref="bsWrapper" flex-1 overflow-hidden h-full>
      <better-scroll
        ref="bsScroll"
        :options="{ scrollX: true, scrollY: false, click: false }"
      >
        <tab-detail @scroll="handleScroll" />
      </better-scroll>
    </div>
    <reload-button />
  </div>
</template>

<script lang="ts" setup>
import { useElementBounding } from "@vueuse/core";
import { useTabStore } from "@/store";
import type { BScrollInstance } from "@better-scroll/core";
import { ReloadButton, TabDetail } from "./components";

const route = useRoute();
const tabStore = useTabStore();

const bsWrapper = ref<HTMLElement>();
const { width: bsWidth, left: bsLeft } = useElementBounding(bsWrapper);

const bsScroll = ref<{ instance: BScrollInstance }>();

const handleScroll = (clientX: number) => {
  const currentX = clientX - bsLeft.value;
  const deltaX = currentX - bsWidth.value / 2;
  if (bsScroll.value) {
    const { maxScrollX, x: leftX } = bsScroll.value.instance;
    const rightX = maxScrollX - leftX;
    const update =
      deltaX > 0 ? Math.max(-deltaX, rightX) : Math.min(-deltaX, -leftX);
    bsScroll.value?.instance.scrollBy(update, 0, 300);
  }
};

const init = () => {
  tabStore.iniTabStore(route);
};

watch(
  () => route.fullPath,
  () => {
    tabStore.addTab(route);
    tabStore.setActiveTab(route.fullPath);
  }
);

// 初始化
init();
</script>
<style scoped>
.global-tab {
  box-shadow: 0 1px 2px rgb(0 21 41 / 8%);
}
</style>
